package com.example.echoewish.ui.my_activity.user_info_activity;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.echoewish.econstant.Constant;
import com.example.echoewish.econstant.UserInfo;
import com.example.echoewish.pojo.Friend;
import com.example.echoewish.repository.ConcernMessageRepository;
import com.example.echoewish.repository.PreConcernRepository;
import com.example.echoewish.repository.UserMessageRepository;
import com.example.echoewish.util.LogUtil;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserInfoShowViewModel extends ViewModel {
    public MutableLiveData<Friend> userMutableLiveData;
    public MutableLiveData<Integer> userIdMutableLiveData;
    public MutableLiveData<String> responseMutableLiveData;

    public UserInfoShowViewModel()
    {
        userMutableLiveData=new MutableLiveData<>();
        userIdMutableLiveData=new MutableLiveData<>();
        responseMutableLiveData=new MutableLiveData<>();
    }

    public void getUserInfo()
    {
        UserMessageRepository.getInstance().getFriendMessage(UserInfo.getInstance().UserId,userIdMutableLiveData.getValue(),new GetUserInfoCallBack());
    }

    public void concernFriend(int userId,int friId)
    {
        PreConcernRepository.getInstance().sendConcernRequest(userId,friId,new ConcernFriendCallback());
    }

    public void cancelConcernFriend(int userId,int friId)
    {
        ConcernMessageRepository.getInstance().cancelConcern(userId,friId,new ConcernFriendCallback());
    }

    private class GetUserInfoCallBack implements Callback<Friend>
    {

        @Override
        public void onResponse(Call<Friend> call, Response<Friend> response) {
            userMutableLiveData.postValue(response.body());
        }

        @Override
        public void onFailure(Call<Friend> call, Throwable t) {
            new LogUtil().w(LogUtil.CALLBACK_TAG,"获取用户信息回调失败"+t);
            userMutableLiveData.postValue(null);
        }
    }

    private class ConcernFriendCallback implements Callback<ResponseBody>
    {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                responseMutableLiveData.postValue(response.body().string());
            } catch (IOException ioException) {
                responseMutableLiveData.postValue(null);
                ioException.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            new LogUtil().w(LogUtil.CALLBACK_TAG,"请求关注好友 回调失败"+t);
            responseMutableLiveData.postValue(Constant.HTTPS_GET_CALLBACK_FAIL);
        }
    }

}
